package com.fishingwithme.android.ui.screens.harvest

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fishingwithme.android.data.model.HarvestRecordDto
import com.fishingwithme.android.data.repository.FishingRepository
import kotlinx.coroutines.flow.firstOrNull

class HarvestPagingSource(
    private val repository: FishingRepository,
    private val spotId: String
) : PagingSource<Int, HarvestRecordDto>() {

    override fun getRefreshKey(state: PagingState<Int, HarvestRecordDto>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, HarvestRecordDto> {
        return try {
            val page = params.key ?: 1
            val pageSize = params.loadSize

            val result = repository.loadSpotHarvestRecords(
                spotId = spotId,
                pageNum = page,
                pageSize = pageSize
            ).firstOrNull()

            result?.fold(
                onSuccess = { pageResponse ->
                    val harvestRecords = pageResponse.records ?: emptyList()
                    val prevKey = if (page == 1) null else page - 1
                    val nextKey = if (page >= (pageResponse.pages ?: 0)) null else page + 1

                    LoadResult.Page(
                        data = harvestRecords,
                        prevKey = prevKey,
                        nextKey = nextKey
                    )
                },
                onFailure = { exception ->
                    LoadResult.Error(exception)
                }
            ) ?: LoadResult.Error(Exception("No data received"))
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}